<?php

/**
 *   OPENSHOP 管理中心公用文件
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: init.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

if (!defined('IN_OS')){
    die('Access Denied');
}

define('OS_ADMIN', true);

error_reporting(E_ALL);

if (__FILE__ == ''){
    die('Fatal error code: 0');
}

/* 取得当前openshop所在的根目录 */
define('ROOT_PATH', str_replace('admin/includes/init.php', '', str_replace('\\', '/', __FILE__)));

/* 初始化设置 */
@ini_set('memory_limit',          '128M');
@ini_set('session.cache_expire',  6000);
@ini_set('session.use_trans_sid', 0);
@ini_set('session.use_cookies',   1);
@ini_set('session.auto_start',    0);
@ini_set('display_errors',        1);

if (DIRECTORY_SEPARATOR == '\\'){
    @ini_set('include_path',      '.;' . ROOT_PATH);
}else{
    @ini_set('include_path',      '.:' . ROOT_PATH);
}

if (file_exists(ROOT_PATH . 'data/config.php')){
    include(ROOT_PATH . 'data/config.php');
}else{
    include(ROOT_PATH . 'includes/config.php');
}

if (defined('DEBUG_MODE') == false){
    define('DEBUG_MODE', 0);
}

if (PHP_VERSION >= '5.1' && !empty($timezone)){
    date_default_timezone_set($timezone);
}

if (isset($_SERVER['PHP_SELF'])){
    define('PHP_SELF', $_SERVER['PHP_SELF']);
}else{
    define('PHP_SELF', $_SERVER['SCRIPT_NAME']);
}

define('MAX_MANAGER', 50);

require(ROOT_PATH . 'includes/inc_constant.php');
require(ROOT_PATH . 'includes/cls_openshop.php');
require(ROOT_PATH . 'includes/cls_error.php');
require(ROOT_PATH . 'includes/lib_time.php');
require(ROOT_PATH . 'includes/lib_base.php');
require(ROOT_PATH . 'includes/lib_common.php');
require(ROOT_PATH . 'admin/includes/lib_main.php');
require(ROOT_PATH . 'admin/includes/cls_exchange.php');

/* 对用户传入的变量进行转义操作。*/
if (!get_magic_quotes_gpc()){
    if (!empty($_GET))
    {
        $_GET  = addslashes_deep($_GET);
    }
    if (!empty($_POST))
    {
        $_POST = addslashes_deep($_POST);
    }

    $_COOKIE   = addslashes_deep($_COOKIE);
    $_REQUEST  = addslashes_deep($_REQUEST);
}

/* 对路径进行安全处理 */
if (strpos(PHP_SELF, '.php/') !== false){
    os_header("Location:" . substr(PHP_SELF, 0, strpos(PHP_SELF, '.php/') + 4) . "\n");
    exit();
}

/* 创建 OPENSHOP 对象 */
$os = new OS($db_name, $prefix);
define('DATA_DIR', $os->data_dir());
define('IMAGE_DIR', $os->image_dir());
define('SOURCE_DIR', $os->source_dir());

define('SOURCE_PATH', ROOT_PATH . $os->source_dir() . '/');
define('FILESYNC_HOST', '../' . SOURCE_DIR);

/* 初始化数据库类 */
require(ROOT_PATH . 'includes/cls_mysql.php');
$db = new cls_mysql($db_host, $db_user, $db_pass, $db_name);
$db_host = $db_user = $db_pass = $db_name = NULL;

/* 创建错误处理对象 */
$err = new os_error('message.tpl');

/* 初始化session */
require(ROOT_PATH . 'includes/cls_session.php');
$sess = new cls_session($db, $os->table('sessions'), $os->table('sessions_data'), 'OSCP_ID');

/* 初始化 action */
if (!isset($_REQUEST['act'])){
    $_REQUEST['act'] = '';
}elseif (($_REQUEST['act'] == 'login' || $_REQUEST['act'] == 'logout' || $_REQUEST['act'] == 'signin') &&
    strpos(PHP_SELF, '/privilege.php') === false){
    $_REQUEST['act'] = '';
}elseif (($_REQUEST['act'] == 'forget_pwd' || $_REQUEST['act'] == 'reset_pwd' || $_REQUEST['act'] == 'get_pwd') &&
    strpos(PHP_SELF, '/get_password.php') === false){
    $_REQUEST['act'] = '';
}

/* 载入系统参数 */
$_CFG = load_config();

// TODO : 登录部分准备拿出去做，到时候把以下操作一起挪过去
if ($_REQUEST['act'] == 'captcha')
{
    include(ROOT_PATH . 'includes/cls_captcha.php');
    $img = new captcha(SOURCE_PATH . 'data/captcha/');
    @ob_end_clean(); //清除之前出现的多余输入
    $img->generate_image();

    exit;
}

require(SOURCE_PATH . 'languages/zh_cn/admin/common.php');
require(SOURCE_PATH . 'languages/zh_cn/admin/log_action.php');

if (file_exists(SOURCE_PATH . 'languages/zh_cn/admin/' . basename(PHP_SELF)))
{
    include(SOURCE_PATH . 'languages/zh_cn/admin/' . basename(PHP_SELF));
}

if (!file_exists(SOURCE_PATH . '/temp/caches'))
{
    @mkdir(SOURCE_PATH . '/temp/caches', 0777);
    @chmod(SOURCE_PATH . '/temp/caches', 0777);
}

if (!file_exists(SOURCE_PATH . '/temp/templates_c/admin'))
{
    @mkdir(SOURCE_PATH . '/temp/templates_c/admin', 0777);
    @chmod(SOURCE_PATH . '/temp/templates_c/admin', 0777);
}

clearstatcache();

/* 如果有新版本，升级 */
if (!isset($_CFG['os_version']))
{
    $_CFG['os_version'] = 'v2.0.5';
}

if (preg_replace('/(?:\.|\s+)[a-z]*$/i', '', $_CFG['os_version']) != preg_replace('/(?:\.|\s+)[a-z]*$/i', '', VERSION)
        && file_exists('../upgrade/index.php'))
{
    // 转到升级文件
    os_header("Location: ../upgrade/index.php\n");

    exit;
}

/* 创建 Smarty 对象。*/
require(ROOT_PATH . 'includes/cls_template.php');
$smarty = new cls_template;

$smarty->template_dir  = ROOT_PATH . 'admin/templates';
$smarty->compile_dir   = SOURCE_PATH . '/temp/templates_c/admin';
if ((DEBUG_MODE & 2) == 2)
{
    $smarty->force_compile = true;
}

$smarty->assign('lang', $_LANG);
$smarty->assign('help_open', $_CFG['help_open']);

if(isset($_CFG['enable_order_check']))  // 为了从旧版本顺利升级到2.5.0
{
    $smarty->assign('enable_order_check', $_CFG['enable_order_check']);
}
else
{
    $smarty->assign('enable_order_check', 0);
}
//print_r($_CFG);
//exit;
$smarty->assign('pre_fetch_img', $_CFG['pre_fetch_img'] );

/* 验证管理员身份 */
if ((!isset($_SESSION['admin_id']) || intval($_SESSION['admin_id']) <= 0) &&
    $_REQUEST['act'] != 'login' && $_REQUEST['act'] != 'signin' &&
    $_REQUEST['act'] != 'forget_pwd' && $_REQUEST['act'] != 'reset_pwd' && $_REQUEST['act'] != 'check_order')
{
    /* session 不存在，检查cookie */
    if (!empty($_COOKIE['OSCP']['admin_id']) && !empty($_COOKIE['OSCP']['admin_pass']))
    {
        // 找到了cookie, 验证cookie信息
        $sql = 'SELECT user_id, user_name, password, action_list, last_login ' .
                ' FROM ' .$os->table('admin_user') .
                " WHERE user_id = '" . intval($_COOKIE['OSCP']['admin_id']) . "'";
        $row = $db->GetRow($sql);

        if (!$row)
        {
            // 没有找到这个记录
            setcookie($_COOKIE['OSCP']['admin_id'],   '', 1);
            setcookie($_COOKIE['OSCP']['admin_pass'], '', 1);
            
            if (!empty($_REQUEST['is_ajax']))
            {
                //make_json_error('对不起,您没有执行此项操作的权限!');
                make_json_alert('对不起,您没有执行此项操作的权限!', 'signin');
            }
            else
            {
                //os_header("Location: privilege.php?act=login\n");
                make_json_alert('对不起,因为您长时间没有操作,请重新登录!', 'signin');
            }

            exit;
        }
        else
        {
        	/* 检查管理员账户是否合法 */
		    if(!is_account_valid($row['user_name'], $row['password']))
		    {
		    	if($_COOKIE['OSCP']['admin_id']) {
		    		make_json_alert('非法管理员账号，请重新登录!', 'signout');
		    	}
		    	else
		    	{
		    		destroy_all();
		    	}
		    }
    
            // 检查密码是否正确
            if (md5($row['password'] . $_CFG['hash_code']) == $_COOKIE['OSCP']['admin_pass'])
            {
            	//登陆的管理员人数是否达到最大限制
				if(reach_max_signin())
				{
					make_json_alert('登陆的管理员账户，已经达到最大(' . MAX_ADMINISTRATOR . '人)限制，请联系开发商!', 'signout');
				}
				
                !isset($row['last_time']) && $row['last_time'] = '';
                if($row['action_list'] == 'all'){
					$action_list = $row['action_list'];
					$role_str = '超级管理员';
    			}else{
		    		$privilege_arr = $db->getAll("SELECT r_f.action_id FROM " . $os->table('acl_role_func') . " r_f LEFT JOIN" . $os->table('acl_role_user') . 
		                        " r_u ON r_u.role_id=r_f.role_id WHERE r_u.user_id=".intval($row['user_id']));		      
		    		if($privilege_arr){
			   			$act_list = array();
						while (list($key, $val) = each($privilege_arr)) {
				    		array_push($act_list, $val['action_id']);
						}
		        		$action_list = trim(((sizeof($act_list)>0)  ?  join(',', $act_list)  :  0), ',');
		   		 	}else{
		    			$action_list = '0';
		    		}
		    
		    		$arr_roles = $db->getAll("SELECT r.role_name FROM " . $os->table('acl_role_user') . " r_u LEFT JOIN" . $os->table('acl_role') . 
		                        " r ON r_u.role_id=r.role_id WHERE r_u.user_id=".intval($row['user_id']));	
		   	 		if($arr_roles){
			    		$roles_list = array();
						while (list($key, $val) = each($arr_roles)) {
				    		array_push($roles_list, $val['role_name']);
						}
		        		$role_str = trim(((sizeof($roles_list)>0)  ?  join(',', $roles_list)  :  '无角色'), ',');
		    		}else{
		    			$role_str = '无角色';
		    		}		    
    			}
                set_admin_session($row['user_id'], $row['user_name'], $action_list, $role_str, $row['last_time']);

                // 更新最后登录时间和IP
                $db->query('UPDATE ' . $os->table('admin_user') .
                            " SET last_login = '" . gmtime() . "', last_ip = '" . real_ip() . "'" .
                            " WHERE user_id = '" . $_SESSION['admin_id'] . "'");
            }
            else
            {
                setcookie($_COOKIE['OSCP']['admin_id'],   '', 1);
                setcookie($_COOKIE['OSCP']['admin_pass'], '', 1);

                if (!empty($_REQUEST['is_ajax']))
                {
                    //make_json_error('对不起,您没有执行此项操作的权限!');
                    make_json_alert('对不起,您没有执行此项操作的权限!', 'signin');
                }
                else
                {
                    //os_header("Location: privilege.php?act=login\n");
                    make_json_alert('对不起,因为您长时间没有操作,请重新登录!', 'signin');
                }

                exit;
            }
        }
    }
    else
    {
        if (!empty($_REQUEST['is_ajax']))
        {
            //make_json_error('对不起,您没有执行此项操作的权限!');
            make_json_alert('对不起,您没有执行此项操作的权限!', 'signin');
        }
        else
        {
            //os_header("Location: privilege.php?act=login\n");
            make_json_alert('对不起,因为您长时间没有操作,请重新登录!', 'signin');
        }

        exit;
    }
}

if ($_REQUEST['act'] != 'login' && $_REQUEST['act'] != 'signin' &&
    $_REQUEST['act'] != 'forget_pwd' && $_REQUEST['act'] != 'reset_pwd' && $_REQUEST['act'] != 'check_order')
{
    $admin_path = preg_replace('/:\d+/', '', $os->url()) . 'admin';
    if (!empty($_SERVER['HTTP_REFERER']) &&
        strpos(preg_replace('/:\d+/', '', $_SERVER['HTTP_REFERER']), $admin_path) === false)
    {
        if (!empty($_REQUEST['is_ajax']))
        {
            //make_json_error('对不起,您没有执行此项操作的权限!');
            make_json_alert('对不起,您没有执行此项操作的权限!', 'signin');
        }
        else
        {
            //os_header("Location: privilege.php?act=login\n");
            make_json_alert('对不起,因为您长时间没有操作,请重新登录!', 'signin');
        }

        exit;
    }
}

$filesync =& init_filesync();

/* 管理员登录后可在任何页面使用 act=phpinfo 显示 phpinfo() 信息 */
if ($_REQUEST['act'] == 'phpinfo' && function_exists('phpinfo'))
{
    phpinfo();
    exit;
}

header('content-type: text/html; charset=' . OS_CHARSET);
header('Expires: Fri, 14 Mar 1980 20:53:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

if ((DEBUG_MODE & 1) == 1)
{
    error_reporting(E_ALL);
}
else
{
    error_reporting(E_ALL ^ E_NOTICE);
}
if ((DEBUG_MODE & 4) == 4)
{
    include(ROOT_PATH . 'includes/lib.debug.php');
}
$guide = &lattice_setting();

/* 判断是否支持gzip模式 */
if (gzip_enabled())
{
    ob_start('ob_gzhandler');
}
else
{
    ob_start();
}
?>